package com.corecmd.tcloud.tcim.ui.chatSessions;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.corecmd.tcloud.tcim.R;
import com.corecmd.tcloud.tcim.apis.ApiChatSessions;
import com.corecmd.tcloud.tcim.common.BaseViewHolder;
import com.corecmd.tcloud.tcim.common.Constant;
import com.corecmd.tcloud.tcim.common.RecyclerViewCommonAdapter;
import com.corecmd.tcloud.tcim.common.RecyclerViewFootViewHolder;
import com.corecmd.tcloud.tcim.ui.main.MainActivity;
import com.corecmd.tcloud.tcim.utils.DateFormatUtil;
import com.corecmd.tcloud.tcim.utils.ImSessionHolder;
import com.corecmd.tcloud.tcim.utils.ThreadPoolFactory;
import com.corecmd.tcloud.tcim.utils.ToastUtil;
import com.corecmd.tcloud.tcimcommon.im.domain.MessageRequestPacket;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : tianshaojiao
 * @version : 1.0
 * @apiNote :
 * @date : 2021/3/2
 * @copyright :
 */
public class ChatSessionDetail extends AppCompatActivity implements View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener {
    private static final int TYPE_FOOTER = 1;
    private static final int TYPE_MESSAGE_MINE = 2;
    private static final int TYPE_MESSAGE_RECEIVED = 3;
    private Context mContext;
    private String chatSessionId;
    private String messageReceiverId;
    private TextView chatSessionReceiverName;
    private BroadcastReceiver broadcastReceiver;
    private List<JSONObject> messages = new ArrayList<>();
    private RecyclerViewCommonAdapter adapter = null;
    SwipeRefreshLayout swipeRefreshLayout;
    private static final int LOADMESSAGES = 1;
    private int currentMessagesPage = 1;
    private int messagesPageSize = 20;
    private int totalPage = 0;
    private  int lastVisibleItemPosition = 0;
    private boolean isLoadingMessages = false;
    private LinearLayoutManager layoutManager;
    RecyclerView recyclerView;
    private Handler messagesHandler = null;
    private LinearLayout mBackToMainActivity;
    private String tokenUserId;
    private Button sendMsgBtn;
    private EditText sendMsgEditText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_session_detail);
        mContext = this;
        getBundleInfo();
        initHandler();
        initView();
        initEvent();
        initData();
        registerBroadcastReceiver();
        loadMessages(false);
    }

    private void initEvent() {
        mBackToMainActivity.setOnClickListener(this);
        sendMsgBtn.setOnClickListener(this);
    }

    private void initData() {
        SharedPreferences sp = getSharedPreferences(Constant.LOGININFOKEY, MODE_PRIVATE);
        tokenUserId = sp.getString(Constant.IMUSERID,"");
        chatSessionReceiverName.setText(messageReceiverId);
    }
    private void registerBroadcastReceiver() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Bundle dataBundle = intent.getExtras();
                if (null != dataBundle){
                    String receivedMsg = dataBundle.getString("messageContent");
                    System.out.println("会话详情界面收到一条消息："+receivedMsg);
                    JSONObject newMessage = new JSONObject();
                    newMessage.put("receiverId",dataBundle.getString("receiverId"));
                    newMessage.put("senderId",dataBundle.getString("senderId"));
                    newMessage.put("messageContent",receivedMsg);
                    JSONArray messageArray = new JSONArray();
                    messageArray.add(newMessage);
                    Message message = new Message();
                    message.what = LOADMESSAGES;
                    Bundle bundle = new Bundle();
                    bundle.putString("messagesArray",messageArray.toJSONString());
                    bundle.putInt("totalPage",0);
                    bundle.putInt("totalRecord",0);
                    bundle.putBoolean("isRefresh",false);
                    message.setData(bundle);
                    messagesHandler.sendMessage(message);

                }
            }
        };
        IntentFilter filter = new IntentFilter(Constant.IM_MESSAGE_BROADCAST_ACTION);
        mContext.registerReceiver(broadcastReceiver, filter);
    }
    public void initView(){
        sendMsgBtn = findViewById(R.id.sendMsgBtn);
        sendMsgEditText = findViewById(R.id.sendMsgEdit);
        mBackToMainActivity = findViewById(R.id.backToMainActivity);
        chatSessionReceiverName = findViewById(R.id.chat_session_receiverName);
        recyclerView = (RecyclerView)findViewById(R.id.msgList_recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.SwipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.blueStatus);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    currentMessagesPage = 1;
                    totalPage = 0;
                    messages.clear();
                    adapter.changeMoreStatus(RecyclerViewCommonAdapter.REFRESHING);
                    loadMessages(false);
                } catch (Exception e) {
                    Log.d("异常","刷新数据时异常:"+e.getMessage());
                }
            }
        });
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerViewCommonAdapter(mContext,layoutManager,new ChatMessageReceivedViewHolderGenerator(),R.layout.chat_message_item_received,messages){
            @Override
            public int getItemViewType(int position) {
                if (position + 1 == getItemCount()) {
                    return TYPE_FOOTER;
                } else {
                    JSONObject messageInfo = (JSONObject) getmData().get(position);
                    if (tokenUserId.equalsIgnoreCase(messageInfo.getString("receiverId"))){
                        return TYPE_MESSAGE_RECEIVED;
                    }
                    return TYPE_MESSAGE_MINE;
                }
            }

            @NonNull
            @Override
            public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                if (viewType == TYPE_FOOTER) {
                    View view = LayoutInflater.from(mContext).inflate(R.layout.loading_foo_loading, parent,
                            false);
                    return new RecyclerViewFootViewHolder(mContext,view);
                }
                else if (viewType == TYPE_MESSAGE_MINE) {
                    View view = LayoutInflater.from(mContext).inflate(R.layout.chat_message_item_mine, parent,
                            false);
                    BaseViewHolder viewHolder = null;
                    try {
                        viewHolder = new ChatMessageMineViewHolderGenerator().generateVieHolder(mContext,layoutManager,view);
                    }catch (Exception e) {
                        System.out.println("获取发送的消息视图异常:"+e.getMessage());
                    }
                    assert viewHolder != null;
                    return viewHolder;
                } else if (viewType == TYPE_MESSAGE_RECEIVED){
                    View view = LayoutInflater.from(mContext).inflate(R.layout.chat_message_item_received, parent,
                            false);
                    BaseViewHolder viewHolder = null;
                    try {
                        viewHolder = new ChatMessageReceivedViewHolderGenerator().generateVieHolder(mContext,layoutManager,view);
                    }catch (Exception e) {
                        System.out.println("获取接收到的消息视图异常:"+e.getMessage());
                    }
                    assert viewHolder != null;
                    return viewHolder;
                }
                return null;
            }

            @Override
            public void convert(final BaseViewHolder holder, Object data) {
                BaseViewHolder messageViewHolder = null;
                if (holder instanceof ChatMessageReceivedViewHolder){
                    messageViewHolder = (ChatMessageReceivedViewHolder)holder;
                    messageViewHolder.bindView(data);
                }
                if (holder instanceof ChatMessageMineViewHolder){
                    messageViewHolder = (ChatMessageMineViewHolder)holder;
                    messageViewHolder.bindView(data);
                }
                final OnItemClickListener onItemClickListener = getOnItemClickListener();
                if (getOnItemClickListener() != null && messageViewHolder != null) {
                    messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int position = holder.getLayoutPosition();
                            onItemClickListener.onItemClick(holder.itemView, position);
                        }
                    });

                    messageViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            int position = holder.getLayoutPosition();
                            onItemClickListener.onItemLongClick(holder.itemView, position);
                            return false;
                        }
                    });
                }
            }
        };
        adapter.setOnItemClickListener(new RecyclerViewCommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ToastUtil.showToaskShort(mContext,"点击消息");
            }
            @Override
            public void onItemLongClick(View view, int position) {
                ToastUtil.showToaskShort(mContext,"长按消息");
            }
        });
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        return;
                    }
                    if (!isLoadingMessages) {
                        currentMessagesPage += 1;
                        //设置正在加载更多
                        adapter.changeMoreStatus(RecyclerViewCommonAdapter.LOADING_MORE);
                        loadMessages(false);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            }
        });
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }
    private void getBundleInfo(){
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("chatSessionInfo");
        JSONObject chatSessionJsonInfo = JSONObject.parseObject(bundle.getString("chatSessionInfo"));
        if (null != chatSessionJsonInfo){
            chatSessionId = chatSessionJsonInfo.getString("id");
            messageReceiverId = chatSessionJsonInfo.getString("receiverId");
        }
    }
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId){
            case R.id.backToMainActivity:
                Intent intent = new Intent( this, MainActivity. class);
                intent.putExtra( "targetFragment", R.id.id_tab_chat_sessions);
                startActivity(intent);
                this.finish();
                break;
            case R.id.sendMsgBtn:
                sendMsgToReceiver();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }
    private void loadMessages(final boolean isRefresh) {
        isLoadingMessages  =  true;
        if (isRefresh){
            swipeRefreshLayout.setRefreshing(true);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = ApiChatSessions.listChatMessages(chatSessionId,currentMessagesPage,messagesPageSize,"");
                JSONArray jsonArrayAlbums = new JSONArray();
                int tmpTotalPage = 0;
                int tmpTotalRecord = 0;
                try {
                    if (null != result){
                        JSONObject jsonResult = JSONObject.parseObject(result);
                        if ("200".equals(jsonResult.getString("statusCode"))){
                            jsonArrayAlbums = jsonResult.getJSONArray("chatSessions");
                            tmpTotalPage = Integer.parseInt(jsonResult.getString("totalPage"));
                            tmpTotalRecord = Integer.parseInt(jsonResult.getString("totalRecord"));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Message message = new Message();
                message.what = LOADMESSAGES;
                Bundle bundle = new Bundle();
                bundle.putString("messagesArray",jsonArrayAlbums.toJSONString());
                bundle.putInt("totalPage",tmpTotalPage);
                bundle.putInt("totalRecord",tmpTotalRecord);
                bundle.putBoolean("isRefresh",isRefresh);
                message.setData(bundle);
                messagesHandler.sendMessage(message);
            }
        }).start();
    }

    private void initHandler() {
        messagesHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                swipeRefreshLayout.setRefreshing(false);
                int msgWhat = msg.what;
                Bundle msgData = msg.getData();
                if (msgWhat == LOADMESSAGES){
                    isLoadingMessages  =  false;
                    try {
                        String dataArray = msgData.getString("messagesArray");
                        JSONArray data = (null != dataArray && !dataArray.isEmpty()) ? JSONObject.parseArray(dataArray):null;
                        boolean isRefresh = msgData.getBoolean("isRefresh");
                        List<JSONObject> newDatas = new ArrayList<>();
                        int loadStatusTips = RecyclerViewCommonAdapter.NO_LOAD_MORE;
                        if (data != null && data.size() > 0){
                            for (int i = 0; i < data.size(); i++){
                                newDatas.add(data.getJSONObject(i));
                            }
                            totalPage = msgData.getInt("totalPage");
                        }
                        if (currentMessagesPage < totalPage){
                            loadStatusTips = RecyclerViewCommonAdapter.PULLUP_LOAD_MORE;
                        }
                        if (isRefresh){
                            messages.clear();
                            adapter.notifyDataSetChanged();
                        }
                        messages.addAll(newDatas);
                        adapter.changeMoreStatus(loadStatusTips);
                    } catch (Exception e) {
                        Log.d("异常","更新视图异常:"+e.getMessage());
                    }
                } else if(msgWhat == R.id.sendMsgBtn){
                    isLoadingMessages  =  false;
                    try {
                        boolean isRefresh = false;
                        List<JSONObject> newDatas = new ArrayList<>();
                        JSONObject sendMessage = new JSONObject();
                        sendMessage.put("receiverId",msgData.getString("receiverId"));
                        sendMessage.put("isSuccess",msgData.getBoolean("isSuccess"));
                        sendMessage.put("messageContent",msgData.getString("messageContent"));
                        sendMessage.put("senderId",msgData.getString("senderId"));
                        newDatas.add(sendMessage);
                        int loadStatusTips = RecyclerViewCommonAdapter.NO_LOAD_MORE;
                        totalPage = 10;
                        if (currentMessagesPage < totalPage){
                            loadStatusTips = RecyclerViewCommonAdapter.PULLUP_LOAD_MORE;
                        }
                        if (isRefresh){
                            messages.clear();
                            adapter.notifyDataSetChanged();
                        }
                        messages.addAll(newDatas);
                        adapter.changeMoreStatus(loadStatusTips);
                        if (msgData.getBoolean("isSuccess")){
                            sendMsgEditText.setText("");
                        } else {
                            ToastUtil.showToaskShort(mContext,"消息发送失败");
                        }
                    } catch (Exception e) {
                        Log.d("异常","更新视图异常:"+e.getMessage());
                    }
                }
                return false;
            }
        });
    }

    public void sendMsgToReceiver(){
        String sendMsg = sendMsgEditText.getText().toString();
        System.out.println(tokenUserId+"发送消息："+sendMsg);
        if (!sendMsg.isEmpty()){
            MessageRequestPacket messageRequestPacket = new MessageRequestPacket();
            messageRequestPacket.setSendTimestamp(DateFormatUtil.getCurrentDateStr());
            messageRequestPacket.setSenderId(tokenUserId);
            messageRequestPacket.setMsgType("5");
            messageRequestPacket.setMsgContentType("1");
            messageRequestPacket.setReceiverId(messageReceiverId);
            messageRequestPacket.setMsgContent(sendMsg);
            //使用线程池发送消息
            ThreadPoolFactory.getSendImMsgThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    boolean isSuccess = ImSessionHolder.sendMessage(tokenUserId,messageRequestPacket);
                    Message msgSendResultMessage = new Message();
                    msgSendResultMessage.what = R.id.sendMsgBtn;
                    Bundle data = new Bundle();
                    data.putBoolean("isSuccess",isSuccess);
                    data.putString("messageContent",messageRequestPacket.getMsgContent());
                    data.putString("receiverId",messageReceiverId);
                    data.putString("senderId",tokenUserId);
                    msgSendResultMessage.setData(data);
                    messagesHandler.sendMessage(msgSendResultMessage);
                }
            });
        } else {
            ToastUtil.showToaskShort(mContext,"发送消息内容不能为空");
        }
    }
    @Override
    public void onGlobalLayout() {
        boolean canScroll = recyclerView.computeVerticalScrollRange() > recyclerView.computeVerticalScrollExtent();
        if (canScroll && !layoutManager.getStackFromEnd()){
            layoutManager.setStackFromEnd(true);
            return;
        }
        if (!canScroll && layoutManager.getStackFromEnd()){
            layoutManager.setStackFromEnd(false);
        }
    }
}
